package kr.co.redcircle.service.oAuth.service;


import org.scribe.model.OAuthConfig;
import org.scribe.model.OAuthConstants;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

public class OAuthForGoogle20ServiceImpl implements OAuthService {

	  private static final String VERSION = "2.0";
	  private static final String GRANT_TYPE = "grant_type";
	  private static final String AUTHORIZATION_CODE = "authorization_code";
		
	  
	  private final DefaultGoogle20Api api;
	  private final OAuthConfig config;
	  
	  public OAuthForGoogle20ServiceImpl(DefaultGoogle20Api google20Api, OAuthConfig config) {

		  this.api = google20Api;
		  this.config = config;
	  }

	/**
	   * {@inheritDoc}
	   */
	  public Token getAccessToken(Token requestToken, Verifier verifier)
	  {
	    OAuthRequest request = new OAuthRequest(Verb.POST, api.getAccessTokenEndpoint());
	    request.addBodyParameter(OAuthConstants.CODE, verifier.getValue());
	    request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
	    request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
	    request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
	    request.addBodyParameter(GRANT_TYPE, AUTHORIZATION_CODE);
	    
	    if(config.hasScope()) request.addBodyParameter(OAuthConstants.SCOPE, config.getScope());

	    Response response = request.send();
	    return api.getAccessTokenExtractor().extract(response.getBody());
	  }
		  

	  /**
	   * {@inheritDoc}
	   */
	  public Token getRequestToken()
	  {
	    throw new UnsupportedOperationException("Unsupported operation, please use 'getAuthorizationUrl' and redirect your users there");
	  }

	  /**
	   * {@inheritDoc}
	   */
	  public String getVersion()
	  {
	    return VERSION;
	  }

	  /**
	   * {@inheritDoc}
	   */
	  public void signRequest(Token accessToken, OAuthRequest request)
	  {
	    request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken());
	  }

	  /**
	   * {@inheritDoc}
	   */
	  public String getAuthorizationUrl(Token requestToken)
	  {
	    return api.getAuthorizationUrl(config);
	  }

}
